// 富文本编辑器
const { createEditor, createToolbar } = window.wangEditor

const editorConfig = {
  placeholder: 'Type here...',
  onChange(editor) {
    const html = editor.getHtml()
    // 也可以同步到 <textarea>
  }
}

const editor = createEditor({
  selector: '#editor-container',
  html: '<p><br></p>',
  config: editorConfig,
  mode: 'default', // or 'simple'
})

const toolbarConfig = {}

const toolbar = createToolbar({
  editor,
  selector: '#toolbar-container',
  config: toolbarConfig,
  mode: 'default', // or 'simple'
})


// 信息查询
const informationInquiry = document.querySelector('.informationInquiry')
// 选课详细
const courseSelection = document.querySelector('.courseSelection')
// about
const about = document.querySelector('.about')
// 选择
const choose = document.querySelectorAll('.navChoose [class^="choose"] ul')   //主要列表功能
const choose3 = document.querySelector('.choose3')  //about的列表
// 获取文章展示区DOM
const essays = document.querySelector('.essays')
// 获取文章DOM对象
const essay = document.querySelector('.essay')
// 获取按钮的DOM对象
const add = document.querySelector('.add')
const deletes = document.querySelector('.delete')
const cancel = document.querySelector('.cancel')
const deleteCancel = document.querySelector('.deleteCancel')
const deleteSure = document.querySelector('.deleteSure')
const adds = document.querySelector('.adds')
const updateCancel = document.querySelector('.updateShowCancel')
const updateSure = document.querySelector('.updateButton')
// 文章新增弹窗
const insertShow = document.querySelector('.insertShow')
// 文章删除弹窗
const deleteShow = document.querySelector('.deleteShow')
// 文章修改弹窗
const updateShow = document.querySelector('.updateShow')
const updateFile = document.querySelector('.updateShow [type="file"]')
const updateShowImg = document.querySelector('.updateShow .filePhotos')
// 文件上传DOM
const file = document.querySelector('.insertShow [type="file"]')
const filePhotos = document.querySelector('.filePhotos')
// 获取新增弹窗标题
const inputLine = document.querySelector('.inputLine')
// 获取删除弹窗标题
const deleteInputLine = document.querySelector('.deleteInputLine')
// 获取修改弹窗标题
const updateShowTitle = document.querySelector('.updateShow .inputLine')
// 控件栏DOM对象
const first = document.querySelector('.first')
const last = document.querySelector('.last')
const next = document.querySelector('.next')
const theLast = document.querySelector('.theLast')
const allPage = document.querySelector('.allPage')
// 输入框对象
const paged = document.querySelector('.paged')
// 页码总数DOM对象
const pageSum = document.querySelector('.controlTable select')
// 定时器
let timeCord = null

// 页码
let page = 1
let pageNumber = 3
// 记录最大页数
let maxPage = 0
// 记录当前页数据行数量
let trNumber
// 记录当前更新文章id
let essayId

// 初始化按钮
!function () {
  function list(e) {
    return () => {
      clearTimeout(timeCord)
      e.style.display = 'block'
    }
  }

  function close(e) {
    return () => {
      timeCord = setTimeout(() => {
        e.style.display = 'none'
      }, 500)
    }
  }

  about.addEventListener('mouseenter', list(choose3))
  about.addEventListener('click', list(choose3))
  about.addEventListener('mouseleave', close(choose3))
  choose3.addEventListener('mouseenter', () => {
    clearTimeout(timeCord)
  })
  choose3.addEventListener('mouseleave', close(choose3))
}()

getPage()

// 关闭弹窗
function close(element) {
  return () => {
    // 设置内容为空
    inputLine.value = file.value = ''
    filePhotos.src = '../../photos/essay2.jpg'
    editor.setHtml('')
    // 隐藏弹窗
    element.style.display = 'none'
  }
}

// 打开弹窗
function open(element) {
  return () => {
    element.style.display = 'block'
  }
}

add.addEventListener('click', open(insertShow))

cancel.addEventListener('click', close(insertShow))

deletes.addEventListener('click', open(deleteShow))

deleteCancel.addEventListener('click', close(deleteShow))

updateCancel.addEventListener('click', close(updateShow))

// 渲染文章列表
function showAllEssay() {
  axios({
    url: 'http://127.0.0.1:8080/Root/Major/download',
    params: {
      page,
      pageNumber
    }
  }).then(result => {
    const htmlStr = result.data.data.map((element, index) => {
      const encodedImage = element.imageBase64String    //Base64字符串
      return `
      <div class="essay" data-id="${index + 1}">
        <img src="${encodedImage == null ? '../../photos/essay2.jpg' : 'data:image/png;base64,' + encodedImage}" alt="">
        <h3>${element.id}. ${element.title}</h3>
        <br>
        <span>${element.textInformation}</span>
      </div>`
    }).join('')
    essays.innerHTML = htmlStr
  })
}

showAllEssay()    //初始化

// 更新数据函数
updateSure.addEventListener('click', () => {
  const newTitle = updateShowTitle.value
  const newImg = updateFile.files[0]
  const textInformation = editor.getHtml()
  axios({
    url: 'http://127.0.0.1:8080/Root/Major/updateEssay',
    method: 'POST',
    data: {
      id: essayId,
      title: newTitle,
      image: newImg,
      textInformation
    }
  }).then(() => {
    updateShow.style.display = 'none'
    showAllEssay()
  }).catch(() => {
    alert('修改失败')
  })
})

// 事件监听
essays.addEventListener('click', async (e) => {
  const element = e.target
  if (!element.classList.contains('essay')) {
    return
  }
  updateShow.style.display = 'block'
  essayId = element.dataset.id
  // 获取返回结果
  const result = (await axios({
    url: 'http://127.0.0.1:8080/Root/Major/getNoneDownloadEssay',
    params: {
      id: essayId
    }
  })).data.data
  updateShowTitle.value = result.title
  updateShowImg.src = result.imageBase64String === null ? '../../photos/essay2.jpg' : 'data:image/png;base64,' + result.imageBase64String
  editor.setHtml(result.textInformation)
})

// 文件上传
file.addEventListener('change', () => {
  const image = file.files[0]
  // 判断上传文件是否为图片
  if (!/^image/.test(image.type)) {
    file.value = ''
    alert('上传的文件必须为图片')
  }
  // 将上传图片显现在img中
  const imageURL = URL.createObjectURL(image)
  filePhotos.src = imageURL
})

updateFile.addEventListener('change', () => {
  const image = updateFile.files[0]
  if (!/^image/.test(image.type)) {
    file.value = ''
    alert('上传的文件必须为图片')
  }
  const imageURL = URL.createObjectURL(image)
  updateShowImg.src = imageURL
})

// 存储数据函数
function saveEssay(availableEssayId, titleInformation, image, editorInformation) {
  // 构建表单对象
  const formData = new FormData()
  formData.append('id', availableEssayId)
  formData.append('title', titleInformation)
  formData.append('textInformation', editorInformation)
  formData.append('image', image)
  axios({
    url: 'http://127.0.0.1:8080/Root/Major/upload',
    method: 'POST',
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    data: {
      id: availableEssayId,
      title: titleInformation,
      textInformation: editorInformation,
      image
    }
  }).then(() => {
    showAllEssay()
    close(insertShow)
    getPage()
    alert('添加成功')
  }).catch(() => {
    alert('添加失败')
  })
}

// 存储数据函数
function saveEssayInit() {
  return () => {
    let availableEssayId
    // 获取可用编号
    axios({
      url: 'http://127.0.0.1:8080/Root/Major/availableEssayId'
    }).then(result => {
      availableEssayId = result.data.data || 1
      const titleInformation = inputLine.value
      const image = file.files[0]
      const editorInformation = editor.getHtml()
      saveEssay(availableEssayId, titleInformation, image, editorInformation)
    })
  }
}

// 存储数据
adds.addEventListener('click', saveEssayInit())

// 删除数据
deleteSure.addEventListener('click', () => {
  const deleteId = deleteInputLine.value
  // 删除相应数据
  axios({
    url: 'http://127.0.0.1:8080/Root/Major/deleteEssay',
    method: 'POST',
    params: {
      deleteId
    }
  }).then(() => {
    getPage()
    close(deleteShow)
    showAllEssay()
  }).catch(() => {
    alert('删除失败')
  })
})

// 获取表格页数
function getPage() {
  axios({
    url: 'http://127.0.0.1:8080/Root/Major/allPage',
    params: {
      pageNumber
    }
  }).then(result => {
    maxPage = allPage.innerHTML = result.data.data
  })
}

// 表格空间监听
first.addEventListener('click', () => {
  page = 1
  showAllEssay(page, pageNumber)
})

last.addEventListener('click', () => {
  if (page > 1) {
    showAllEssay(--page, pageNumber)
  }
})

next.addEventListener('click', () => {
  console.log(page);
  if (page < maxPage) {
    showAllEssay(++page, pageNumber)
  }
})

theLast.addEventListener('click', () => {
  page = maxPage
  showAllEssay(page, pageNumber)
})

pageSum.addEventListener('change', () => {
  pageNumber = pageSum.value
  page = 1
  showAllEssay(page, pageNumber)
})

paged.addEventListener('change', () => {
  page = paged.value
  // 限定page范围
  page = page > maxPage ? maxPage : page
  page = page < 1 ? 1 : page
  showAllEssay(page, pageNumber)
})